package de.kandlin.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import de.kandlin.db.HibernateUtil;
import de.kandlin.model.Human;

public class HumanDataPersistenceService {
	
	private static final Logger logger = Logger.getLogger(HumanDataPersistenceService.class);
	
	public HumanDataPersistenceService() {
	}

	public void storeData(Human human) {
		emptyTable();
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		session.save(human);
		transaction.commit();
		session.close();
	}

	public Human loadData() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		@SuppressWarnings("unchecked")
		List<Human> humans = (List<Human>) session.createQuery("select h from Human as h").list();
		transaction.commit();
		session.close();
		Human human = null;
		if (humans.size() > 0) {
			human = humans.get(0);
		}
		logger.debug("geladen: " + human);
		return human;
	}
	
	private void emptyTable() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		session.createQuery("delete from Human").executeUpdate();
		transaction.commit();
	}
}
